from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, get_object_or_404
from models import Note
import datetime

from django_openidconsumer.views import signout as oid_signout

def index(request):
    return render_to_response('index.html', {
        'user'        : request.user,
        'recent_notes': Note.objects.all().order_by('-created')[:5]
    })

def user_index(request, username):
    other_user = get_object_or_404(User, username=username)
    return render_to_response('user.html', {
        'other_user': other_user,
        'user': request.user,
    })

def note(request, note_id):
    note = get_object_or_404(Note, pk=note_id)
    return render_to_response('note.html', {
        'note': note,
        'user': request.user,
    })

@login_required
def create(request):
    if request.method == 'POST':
        note = Note(
            body = request.POST.get('body', ''),
            created = datetime.datetime.now(),
            updated = datetime.datetime.now(),
            user = request.user,
        )
        note.save()
        return HttpResponseRedirect('/note/%d/' % note.id)

    return render_to_response('create.html', {
        'user': request.user,
    })

@login_required
def edit(request, note_id):
    note = get_object_or_404(Note, pk=note_id)
    if request.user.id != note.user_id:
        return HttpResponseForbidden("You do not own that note")
    
    if request.method == 'POST':
        note.body = request.POST.get('body', '')
        note.updated = datetime.datetime.now()
        note.save()
        
        return HttpResponseRedirect('/note/%d/' % note.id)
    
    return render_to_response('edit.html', {
        'note': note,
        'user': request.user,
    })

def logout_view(request):
    logout(request)
    oid_signout(request)
    return HttpResponseRedirect('/')